<template>
  <div class="notice-manage">
    <!-- 查询条件区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="创建人">
        <el-input v-model="searchForm.createBy" placeholder="请输入创建人"></el-input>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="searchForm.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="handleQuery">查询</el-button>
        <el-button type="info" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格区域 -->
    <el-table :data="tableData" >
      <el-table-column prop="index" label="序号" align="center" width="80">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" align="center"></el-table-column>
      <el-table-column prop="createBy" label="创建人" align="center"></el-table-column>
      <el-table-column prop="publishTime" label="发布时间" align="center">
        <template slot-scope="scope">
          <span>{{parseTime(scope.row.publishTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button type="info" size="mini" @click="handlePreview(scope.row)">预览</el-button>
          <el-button type="info" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <pagination v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="loadData"
    />

    <!-- 新增通知弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="新增通知公告">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="选择栏目" prop="columnId">
          <el-select v-model="addForm.columnId" placeholder="请选择栏目" clearable  >
            <el-option v-for="column in columnList" :key="column.columnId" :label="column.columnName"
                       :value="column.columnId" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择发布时间">
          <!-- 开始时间选择器 -->
          <el-date-picker
            v-model="startTime"
            style="width: 240px; margin-right: 10px"
            value-format="yyyy-MM-dd"
            placeholder="开始时间"
            @change="handleTimeChange"
          ></el-date-picker>
          <!-- 结束时间选择器 -->
          <el-date-picker
            v-model="endTime"
            type="date"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            placeholder="结束时间"
            @change="handleTimeChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="选择文章">
          <el-select v-model="addForm.articleId" placeholder="请选择文章"  >
            <el-option v-for="article in articleList" :key="article.articleId" :label="article.articleName"
                       :value="article.articleId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddPreview">预览</el-button>
          <el-button @click="submitAddForm">添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 使用导入的预览组件 -->
    <ArticlePreview
      :article="previewArticle"
      :visible.sync="previewVisible"
      :columnList="columnList"
      :loading="loading"
    />
  </div>
</template>

<script>
import { listNotice, addNotice, delNotice ,selectArticle} from "@/api/publish/notice";
import { listColumn } from "@/api/publish/column";
import ArticlePreview from "@/views/publish/article/ArticlePreview.vue";
import { getPost } from "@/api/publish/post";

export default {
  name: 'NoticePreview',
  dicts: ['sys_normal_disable', 'wa_publish_article', 'wa_dict_type'],
  components: {
    ArticlePreview
  },
  data() {
    return {
      // 预览弹窗显示状态
      previewVisible: false,
      // 预览的文章数据
      previewArticle: {
        title: '',
        subTitle: '',
        content: '',
        cover: '',
        columnId: '',
        createBy: '',
        createTime: ''
      },
      // 分页参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        columnId: undefined,
        status: undefined
      },
      total: 0,
      // 开始时间
      startTime: '',
      // 结束时间
      endTime: '',
      // 查询表单数据
      searchForm: {
        createBy: '',
        title: '',
        publishTime: '',
      },
      // 存储符合时间范围的栏目
      columnList: [],
      // 存储符合栏目+时间范围的文章
      articleList: [],
      // 表格数据
      tableData: [],
      // 新增弹窗显示控制
      dialogVisible: false,
      // 新增表单数据
      addForm: {
        //选中的栏目Id
        columnId: '',
        //选中的文章Id
        articleId: ''
      },
      // 加载状态
      loading: false,
      // 表单数据
      form: {
        columnId: undefined,
        articleId: undefined,
        publicTime: undefined
      }
    }
  },
  created() {
    // 组件创建时加载数据
    this.loadData();

  },
  watch: {
    'addForm.columnId'(newVal) {
      if (!this.startTime || !this.endTime || !newVal) {
        this.addForm.articleId = '';
        this.articleList = [];
      }
      this.loadArticlesByColumnAndTime(newVal);
    }
  },
  methods: {

    // 加载数据
    loadData(page, limit) {
      if (page) this.queryParams.pageNum = page;
      if (limit) this.queryParams.pageSize = limit;
      listNotice(this.queryParams).then(response => {
        this.tableData = response.rows || [];
        this.total = response.total || 0;
      });
    },
    // 加载指定栏目间范围的文章
    loadArticlesByColumnAndTime(columnId) {
      this.articleList = [];
      selectArticle({
        // 选中的栏目ID
        columnId: columnId,
        // 用户选择的开始时间
        startTime: this.startTime,
        // 用户选择的结束时间
        endTime: this.endTime
      }).then(response => {
        if (response.code === 200) {
          this.articleList = response.data || [];
          if (this.articleList.length === 0) {
            this.$message.info('该栏目在当前时间范围内无文章');
          }
        } else {
          this.$message.error('加载文章失败：' + response.msg);
        }
      }).catch(error => {
        console.error('栏目时间筛选文章失败：', error);
        this.$message.error('网络异常，无法加载文章');
      });
    },
//验证时间，栏目，文章是否完整
    validateAll() {
      //时间验证
      if (!this.startTime) {
        this.$message.warning('请选择开始时间');
        return false;
      }
      if (!this.endTime) {
        this.$message.warning('请选择结束时间');
        return false;
      }
      if (new Date(this.startTime) > new Date(this.endTime)) {
        this.$message.error('开始时间不能晚于结束时间');
        return false;
      }
      // 栏目验证
      if (!this.addForm.columnId) {
        this.$message.warning('请选择栏目（需先选择有效时间范围）');
        return false;
      }
      //  文章验证
      if (!this.addForm.articleId) {
        this.$message.warning('请选择文章（需先选择有效栏目）');
        return false;
      }
      return true;
    },
    // 查询按钮点击事件
    handleQuery() {
      this.queryParams.title = this.searchForm.title;       // 标题
      this.queryParams.createBy = this.searchForm.createBy; // 创建人
      this.loadData();
    },
    // 新增按钮点击事件
    handleAdd() {
      // 重置表单数据
      this.addForm = {
        columnId: '',
        articleId: '',
      };
      this.startTime = '';
      this.endTime = '';
      this.columnList = [];
      this.articleList = [];
      this.dialogVisible = true;
      // 显示弹窗
      this.dialogVisible = true;
    },

    handleTimeChange() {
      if (!this.startTime || !this.endTime) {
        this.addForm.columnId = '';
        this.addForm.articleId = '';
        this.columnList = [];
        this.articleList = [];
        return;
      }
      // 调用接口加载栏目与选择发布时间有关的栏目
      this.loadColumnsByTimeRange();
    },
    // 加载符合时间范围的栏目
    loadColumnsByTimeRange() {
      this.columnList = [];
      // 调用栏目列表接口，传递用户选择的时间范围
      listColumn({
        // 用户选择的开始时间
        startTime: this.startTime,
        // 用户选择的结束时间
        endTime: this.endTime
      }).then(response => {
        if (response.code === 200) {
          this.columnList = response.rows || [];
          if (this.columnList.length === 0) {
            this.$message.info('该时间范围内无可用栏目（栏目自身发布时间不匹配）');
          }
        } else {
          this.$message.error('加载栏目失败：' + response.msg);
        }
      }).catch(error => {
        console.error('时间筛选栏目失败：', error);
        this.$message.error('网络异常，无法加载栏目');
      });
    },
    // 提交新增表单
    submitAddForm() {
      if (!this.validateAll()) {
        return;
      }
      const noticeData = {
        columnId: this.addForm.columnId,
        articleId: this.addForm.articleId,
        startTime: this.startTime,
        endTime: this.endTime,
      }
      addNotice(noticeData).then(response => {
        if (response.code === 200) {
          this.$message.success('新增通知成功');
          this.dialogVisible = false;
          this.loadData();
        } else {
          this.$message.error('新增失败:' + response.data)
        }
      });
    },
    //新增图片新闻的弹窗
    handleAddPreview() {
      if (!this.addForm.articleId) {
        this.$message.warning('请先选择文章在进行预览');
        return;
      }
      // 加载选中文章的详情
      getPost(this.addForm.articleId)
        .then((response) => {
          this.previewArticle = {...response.data}
          this.previewVisible = true;
        }).catch((error) => {
        this.$message.error(`预览失败：${error.message || '获取文章数据异常'}`);
      });
    },

    // 文章预览
    handlePreview(row) {
      // 校验文章ID有效性
      if (!row || !row.articleId) {
        this.$message.error('无效的文章ID');
        return;
      }
      this.loading = true; // 显示加载状态
      // 调用接口获取文章详情
      getPost(row.articleId)
        .then((response) => {
          // 存储文章数据到预览对象
          this.previewArticle = {...response.data};
          // 显示预览弹窗
          this.previewVisible = true;
        })
        .catch((error) => {
          this.$message.error(`预览失败：${error.message || '获取文章数据异常'}`);
        })
        .finally(() => {
          this.loading = false; // 关闭加载状态
        });
    },

    // 删除按钮点击事件
    handleDelete(row) {
      // 确认删除（传递noticeId）
      this.$confirm('此操作将删除该通知公告，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除通知公告的接口，传递noticeId
        delNotice(row.noticeId).then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功！'
            });
            this.loadData(); // 重新加载列表
          } else {
            this.$message.error(response.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除失败：', error);
          this.$message.error('删除失败，请重试');
        });
      }).catch(() => {
        this.$message({type: 'info', message: '已取消操作'});
      });
    }
  }
}
</script>

<style scoped>
.notice-manage {
  padding: 20px;
}

.search-form {
  margin-bottom: 15px;
}

.tip-box {
  display: flex;
  align-items: center;
  margin-top: 10px;
  color: #666;
  cursor: pointer;
}

.tip-box i {
  margin-right: 5px;
  color: #409eff;
}
</style>
